package com.masq.aboard.service.impl;

import com.masq.aboard.common.enums.ResultCode;
import com.masq.aboard.common.exceptions.BaseException;
import com.masq.aboard.config.FileConfig;
import com.masq.aboard.dao.FileInfoRepository;
import com.masq.aboard.entity.FileInfoEntity;
import com.masq.aboard.service.FileInfoService;
import com.masq.aboard.service.FileManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * @author masq
 * @since 2024-05-03
 */
@Service
@Transactional
public class FileInfoServiceImpl implements FileInfoService {


    private final FileInfoRepository fileInfoRepository;

    private final FileConfig fileConfig;


    private FileManagerService fileManagerService;

    @Autowired
    public FileInfoServiceImpl(FileInfoRepository fileInfoRepository, FileConfig fileConfig, ApplicationContext context) {
        this.fileInfoRepository = fileInfoRepository;
        this.fileConfig = fileConfig;
        String serviceName = fileConfig.getType().getServiceName();
        this.fileManagerService = (FileManagerService) context.getBean(serviceName);
    }

    @Override
    public FileInfoEntity saveFileInfo(MultipartFile file, String businessId, String businessType) {
        // 保存文件
        String originalFilename = file.getOriginalFilename();
        if (originalFilename != null) {
            String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
            InputStream inputStream = null;
            try {
                 inputStream = file.getInputStream();
            } catch (IOException e) {
                throw new BaseException(ResultCode.FILE_UPLOAD_ERROR, e);
            }
            return saveFileInfo(inputStream, ext, originalFilename, businessId, businessType);
        }
        return null;
    }

    @Override
    public FileInfoEntity saveFileInfo(InputStream inputStream, String ext, String fileName, String businessId, String businessType) {
        String filePath = fileManagerService.uploadFile(inputStream, ext);
        FileInfoEntity fileInfoEntity = new FileInfoEntity();
        fileInfoEntity.setBusinessType(businessType);
        fileInfoEntity.setBusinessId(businessId);
        fileInfoEntity.setFileName(fileName);
        fileInfoEntity.setFilePath(filePath);
        fileInfoEntity.setSaveType(fileConfig.getType().getType());
        fileInfoEntity.setCreateTime(new Date());
        return fileInfoRepository.save(fileInfoEntity);
    }
}
